package com.xiaoxin.smartbi.manager;

import com.xiaoxin.smartbi.common.ErrorCode;
import com.xiaoxin.smartbi.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 基于redisson实现的限流服务
 */
@Service
public class RateLimiterManager {
    @Resource
    RedissonClient redissonClient;

    public void rateLimiter(String key){
        //创建以key为唯一的限流器
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        //每秒发2个令牌
        rateLimiter.trySetRate(RateType.OVERALL, 2, 100, RateIntervalUnit.MILLISECONDS);
        //调用一次消耗一个令牌
        boolean b = rateLimiter.tryAcquire(2);
        if(!b){
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST);
        }
    }
}
